<?php
namespace Services;

use Helpers\Tool;
use Helpers\Main;
use Helpers\User;
use Helpers\HttpClient;
use Helpers\HttpResponse;
use Helpers\XhException;
use Admin\Models\read\Comment;

class Read {

    /**
     * @var \Helpers\HttpClient
     */
    public static $httpClient;
    public static $url;

    const ENUM = [
        'comment'  => [
            'status'    => [0 => '未审核', 1 => '正常', 2 => '删除', 3 => '屏蔽', 4 => '审核未通过']
        ],
    ];

    /**
     * 初始化配置
     *
     * @throws XhException
     *
     * create by ck 20180510
     */
    private static function init()
    {
        if (!self::$httpClient) {
            $config     = Main::getConfigByName('readDB');
            self::$url  = Tool::getValue($config, 'url');
            if (!self::$url) {
                throw new XhException('服务url获取失败');
            }
            self::$httpClient = new HttpClient(self::$url);
        }
    }

    /**
     * 检查错误并获取结果
     *
     * @param HttpResponse $response
     * @throws XhException
     * @return array|bool
     *
     * create by ck 20180604
     */
    public static function getResult(HttpResponse $response)
    {
        if (!$response->isSuccess()) {
            throw new XhException('操作失败', $response);
        }
        $body = $response->toArray();
        if (isset($body['code']) && $body['code'] != 2000) {
            throw new XhException(Tool::getValue($body, 'msg', '请求失败'), $response);
        }
        return Tool::getValue($body, 'results', true);
    }

    /**
     * 刷新栏目
     *
     * @return array|bool
     *
     * create by ck 20180605
     */
    public static function refreshChannel()
    {
        self::init();
        $response = self::$httpClient->post('/api/v1/channels/refresh');
        return self::getResult($response);
    }

    public static function a($refreshData)
    {
        $channelIdArr = array_keys($refreshData);
        $channelIdArr = Channel::find([
            'columns'    => 'id,learnstages',
            'conditions' => 'status = 1 AND type = 1 AND id IN ({idArr:array})',
            'bind'       => ['idArr' => $channelIdArr]
        ])->toArray();
        $channelStage = array_column($channelIdArr, 'learnstages', 'id');
        //处理结构
        $requestData = ['actionType' => $actionType];
        foreach($refreshData as $channelId => $articleIds){
            $requestData['list'][] = ['channelId' => $channelId, 'articleList' => explode(',', $articleIds), 'learnStages' => $channelStage[$channelId]];
        }
//            $httpClient->setHeader('Content-Type', 'application/json');
        $response = $httpClient->postJson('/api/v1/articles/release', $requestData);
    }

    public static function getComments($page = 1, $size = 50, $params = [])
    {

    }

    /**
     * 获取单条评论详情
     *
     * @param $id
     * @return array
     *
     * create by ck 20180530
     */
    public static function getSingleComment($id)
    {
        $obj = Comment::findFirst($id)->toArray();
        Tool::runEnum($obj, self::ENUM['comment']);
        return $obj;
    }

    /**
     * 设置评论状态
     *
     * @param $ids
     * @param $status
     * @throws XhException
     * @return array|bool
     *
     * create by ck 20180530
     * modify by ck 20180604
     */
    public static function setCommentStatus($ids, $status)
    {
        self::init();
        $response = self::$httpClient->postJson('/api/v1/manage/comments', [
            'actionType'    => $status,
            'commentIdList' => $ids,
            'operatorId'    => intval(User::getId()),
            'operatorName'  => Main::getLoginUserInfo('userName')
        ]);
        return self::getResult($response);
    }

    /**
     * 设置星级
     *
     * @param $ids
     * @param $star
     * @throws XhException
     * @return array|bool
     *
     * create by ck 20180531
     * modify by ck 20180604
     * modify by qgz 20181024 使用新接口
     */
    public static function setCommentStar($ids, $star)
    {
        self::init();
//        $response = self::$httpClient->postJson('/api/v1/comments/manage', [
        $response = self::$httpClient->postJson('/api/v1/manage/comments', [
            'actionType'    => 6,
            'commentIdList' => $ids,
            'star'          => intval($star),
            'operatorId'    => intval(User::getId()),
            'operatorName'  => Main::getLoginUserInfo('userName')
        ]);
        return self::getResult($response);
    }

    /**
     * 获取敏感词列表
     *
     * @param int $page
     * @param int $size
     * @param string $keyword
     * @param int $sort
     * @return array
     * @throws XhException
     *
     * create by ck 20180511
     */
    public static function getSensitive($page = 1, $size = 50, $keyword = '', $sort = 0)
    {
        self::init();
        $response = self::$httpClient->get('/api/v1/sensitive', ['pageNo' => $page - 1, 'pageSize' => $size, 'sort' => $sort, 'keyword' => $keyword]);
        $body = self::getResult($response);
        return ['total' => $body['totalCount'], 'rows' => $body['data']];
    }

    /**
     * 增加敏感词
     *
     * @param $words
     * @return bool
     * @throws XhException
     *
     * create by ck 20180511
     */
    public static function addSensitive($words)
    {
        self::init();
        $response = self::$httpClient->postJson(sprintf('/api/v1/sensitive/%s', User::getId()), ['words' => $words]);
        return self::getResult($response);
    }

    /**
     * 删除敏感词(暂只支持删除一个)
     *
     * @param array $ids
     * @return bool
     * @throws XhException
     *
     * create by ck 20180511
     */
    public static function delSensitive($ids = [])
    {
        self::init();
        if (!$ids[0]) {
            throw new XhException('数据为空');
        }
        $response = self::$httpClient->delete(sprintf('/api/v1/sensitive/%s', $ids[0]));
        return self::getResult($response);
    }

    /**
     * 获取文章列表
     *
     * @param $params
     *
     * @return array|bool
     * @throws XhException
     *
     * create by qgz 20181022
     */
    public static function getArticleList($params)
    {
        self::init();
        $response = self::$httpClient->postJson('/api/v1/manage/articlelist', $params);
        $body = $response->toArray();
        if (isset($body['code']) && $body['code'] != 2000) {
            throw new XhException(Tool::getValue($body, 'msg', '请求失败'), $response);
        }
        return $body;
    }

    /**
     * 获取栏目列表
     *
     * @param $params
     *
     * @return array|bool
     * @throws XhException
     *
     * create by qgz 20181022
     */
    public static function getChannelList($params)
    {
        self::init();
        $response = self::$httpClient->postJson('/api/v1/manage/channellist', $params);
        if (!$response->isSuccess()) {
            throw new XhException('操作失败', $response);
        }
        $body = $response->toArray();
        if (isset($body['code']) && $body['code'] != 2000) {
            throw new XhException(Tool::getValue($body, 'msg', '请求失败'), $response);
        }
        return $body;
    }

    /**
     * 获取连载列表
     *
     * @param $params
     *
     * @return array|bool
     * @throws XhException
     *
     * create by qgz 20181022
     */
    public static function getLabelList($params)
    {
        self::init();
        $response = self::$httpClient->postJson('/api/v1/manage/labelList', $params);
        if (!$response->isSuccess()) {
            throw new XhException('操作失败', $response);
        }
        $body = $response->toArray();
        if (isset($body['code']) && $body['code'] != 2000) {
            throw new XhException(Tool::getValue($body, 'msg', '请求失败'), $response);
        }
        return $body;
    }

    /**
     * 添加文章
     *
     * @param $params
     *
     * @return array|bool|mixed|\stdClass
     * @throws XhException
     *
     * create by qgz 20181022
     */
    public static function addArticle($params)
    {
        self::init();
        $response = self::$httpClient->postJson('/api/v1/manage/article', $params);
        if (!$response->isSuccess()) {
            throw new XhException('操作失败', $response);
        }
        $body = $response->toArray();
        if (isset($body['code']) && $body['code'] != 2000) {
            throw new XhException(Tool::getValue($body, 'msg', '请求失败'), $response);
        }
        return $body;
    }

    /**
     * 修改文章
     *
     * @param $params
     *
     * @return array|bool|mixed|\stdClass
     * @throws XhException
     *
     * create by qgz 20181022
     */
    public static function modifyArticle($params)
    {
        self::init();
        $response = self::$httpClient->putJson('/api/v1/manage/article', $params);
        if (!$response->isSuccess()) {
            throw new XhException('操作失败:' . '参数：' . json_encode($params) . '；返回值：' . json_encode($response->toArray(), JSON_UNESCAPED_UNICODE));
        }
        $body = $response->toArray();
        if (isset($body['code']) && $body['code'] != 2000) {
            throw new XhException(Tool::getValue($body, 'msg', '请求失败'), $response);
        }
        return $body;
    }

    /**
     * 删除文章
     *
     * @param $params
     *
     * @return array|bool|mixed|\stdClass
     * @throws XhException
     *
     * create by qgz 20181022
     */
    public static function delArticle($params)
    {
        self::init();
        $response = self::$httpClient->postJson('/api/v1/manage/articles/release', $params);
        if (!$response->isSuccess()) {
            throw new XhException($response);
        }
        $body = $response->toArray();
        if (isset($body['code']) && $body['code'] != 2000) {
            throw new XhException($response);
        }
        return $body;
    }

    /**
     * 删除文章评论
     *
     * @param $userInfo
     * @param $params
     *
     * @return array|bool|mixed|\stdClass
     * @throws XhException
     *
     * create by qgz 20181024
     */
    public static function delComment($userInfo, $params)
    {
        $queryParams = ['userId' => $userInfo['userId'], 'userName' => $userInfo['userName']];
        self::init();
        $response = self::$httpClient->setBodyParams($params, true)->delete('/api/v1/manage/comment', $queryParams);
        if (!$response->isSuccess()) {
            throw new XhException('操作失败', $response);
        }
        $body = $response->toArray();
        if (isset($body['code']) && $body['code'] != 2000) {
            throw new XhException(Tool::getValue($body, 'msg', '请求失败'), $response);
        }
        return $body;
    }

    /**
     * 添加栏目或连载
     *
     * @param $params
     *
     * @return array|bool|mixed|\stdClass
     * @throws XhException
     *
     * create by qgz 20181023
     */
    public static function addChannelOrLabel($params)
    {
        self::init();
        $response = self::$httpClient->postJson('/api/v1/manage/channel', $params);
        if (!$response->isSuccess()) {
            throw new XhException('操作失败', $response);
        }
        $body = $response->toArray();
        if (isset($body['code']) && $body['code'] != 2000) {
            throw new XhException(Tool::getValue($body, 'msg', '请求失败'), $response);
        }
        return $body;
    }

    /**
     * 修改栏目或连载
     *
     * @param $params
     *
     * @return array|bool|mixed|\stdClass
     * @throws XhException
     *
     * create by qgz 20181024
     */
    public static function modifyChannelOrLabel($params)
    {
        self::init();
        $response = self::$httpClient->putJson('/api/v1/manage/channel', $params);
        if (!$response->isSuccess()) {
            throw new XhException('操作失败', $response);
        }
        $body = $response->toArray();
        if (isset($body['code']) && $body['code'] != 2000) {
            throw new XhException(Tool::getValue($body, 'msg', '请求失败'), $response);
        }
        return $body;
    }

    /**
     * 删除栏目或连载
     *
     * @param $userId
     * @param $params
     *
     * @return array|bool|mixed|\stdClass
     * @throws XhException
     *
     * create by qgz 20181024
     */
    public static function delChannelOrLabel($userId, $params)
    {
        self::init();
        $response = self::$httpClient->setBodyParams($params, true)->delete('/api/v1/manage/channel', ['userId' => $userId]);
        if (!$response->isSuccess()) {
            throw new XhException('操作失败', $response);
        }
        $body = $response->toArray();
        if (isset($body['code']) && $body['code'] != 2000) {
            throw new XhException(Tool::getValue($body, 'msg', '请求失败'), $response);
        }
        return $body;
    }

    /**
     * 获取文章详情
     *
     * @param $id
     *
     * @return array|bool
     * @throws XhException
     *
     * create by qgz 20181023
     */
    public static function getArticleData($id)
    {
        self::init();
        $response = self::$httpClient->get('/api/v1/manage/article', ['articleId' => $id]);
        if (!$response->isSuccess()) {
            throw new XhException('操作失败', $response);
        }
        $body = $response->toArray();
        if (isset($body['code']) && $body['code'] != 2000) {
            throw new XhException(Tool::getValue($body, 'msg', '请求失败'), $response);
        }
        return $body;
    }

    /**
     * 获取评论列表
     *
     * @param $params
     *
     * @return array|bool|mixed|\stdClass
     * @throws XhException
     *
     * create by qgz 20181024
     */
    public static function getCommentList($params)
    {
        self::init();
        $response = self::$httpClient->postJson('/api/v1/manage/commentList', $params);
        $body = $response->toArray();
        if (isset($body['code']) && $body['code'] != 2000) {
            throw new XhException(Tool::getValue($body, 'msg', '请求失败'), $response);
        }
        return $body;
    }

    /**
     * 评论管理
     *
     * @param $params
     *
     * @return array|bool|mixed|\stdClass
     * @throws XhException
     *
     * create by qgz 20181024
     */
    public static function setCommentManage($params)
    {
        self::init();
        $response = self::$httpClient->postJson('/api/v1/manage/comments', $params);
        $body = $response->toArray();
        if (isset($body['code']) && $body['code'] != 2000) {
            throw new XhException(Tool::getValue($body, 'msg', '请求失败'), $response);
        }
        return $body;
    }

}